// 水管类
const gameDom = document.querySelector('.game')
const gameWidth = parseFloat(getComputedStyle(gameDom).width)

class Pipe extends RectTangle{
    // dom需要我们去新创建
    constructor(height, top, speed, dom) {
        super(52, height, gameWidth, top, speed, 0, dom)
        this.checked = false
    }
    onMove() {
        if(this.left < -this.width) {
            this.dom.remove()
        }
    }
}

function randomHeight(min, max) {
    return Math.floor(Math.random() * (max - min) + min)
}

// 水管对类
class PipePair {
    constructor(speed) {
        this.spaceHeight = 150 // 水管间空隙的位置
        this.minHeight = 80 // 水管的最小高度
        this.maxHeight = landTop - this.minHeight - this.spaceHeight
        let upHeight = randomHeight(this.minHeight, this.maxHeight) // 获取最小高度
        const downTop = upHeight + this.spaceHeight
        const downHeight = skyHeight - upHeight - this.spaceHeight

        // 创建一个上水管
        const upDom = document.createElement('div')
        upDom.className = 'pipe up'
        // 每个水管对都包含上下柱子属性
        this.upPipe = new Pipe(upHeight, 0, speed, upDom)

        // 创建一个下水管
        const downDom = document.createElement('div')
        downDom.className = 'pipe down'
        
        this.downPipe = new Pipe(downHeight, downTop, speed, downDom)

        gameDom.appendChild(upDom)
        gameDom.appendChild(downDom)
    }

    get useless() {
        return this.upPipe.left < -this.upPipe.width
    }

    move(duration) {
        this.upPipe.move(duration)
        this.downPipe.move(duration)
    }
}

// 水管对生产商
class PipePairProducer {
    constructor(speed) {
        this.speed = speed
        this.pairs = []
        this.timer = null
        this.tick = 1500
    }

    // 开始生产水管对
    startProduce() {
        if(this.timer) {
            return
        }
        this.timer = setInterval(() => {
            this.pairs.push(new PipePair(this.speed))
            // 移除掉出视野的水管
            for(let i = 0; i < this.pairs.length; i++) {
                var pair = this.pairs[i];
                if(pair.useless) {
                    this.pairs.splice(i, 1)
                    i--
                }
            }
        }, this.tick)
    }

    stopProduce() {
        clearInterval(this.timer)
        this.timer = null;
    }

}